/*
 * WorkPool.cpp
 *
 *  Created on: Nov 17, 2008
 *      Author: Ryan
 */

#include "WorkPool.h"

#include "Worker.h"

WorkPool::WorkPool( int numWorkers ) :
	_numWorkers( numWorkers )
{

}

WorkPool::~WorkPool()
{

}

void WorkPool::startWorkers()
{
	for( int i = 0; i < _numWorkers; ++i )
		_workers.create_thread( boost::bind( &Worker::run, new Worker(this) ) );
}

void WorkPool::stopWorkers()
{

	_workers.interrupt_all();
	_workers.join_all();
}

void WorkPool::submitWorkUnit( WorkUnit* work )
{
	boost::mutex::scoped_lock lock( _mutex );

	_jobs.push( work );

	_jobQueueEmpty.notify_one();
}

WorkUnit* WorkPool::getWorkUnit()
{
	boost::mutex::scoped_lock lock( _mutex );

	while( _jobs.empty() )
		_jobQueueEmpty.wait( lock );

	WorkUnit* ret = _jobs.front();
	_jobs.pop();

	return ret;
}
